package com.kedacom.ctsp.authz.oauth2.controller;

import com.kedacom.ctsp.authority.constant.AuthorizeConstant;
import com.kedacom.ctsp.authz.Authorize;
import com.kedacom.ctsp.authz.entity.Authentication;
import com.kedacom.ctsp.authz.exception.UnauthorizedException;
import com.kedacom.ctsp.authz.oauth2.entity.Client;
import com.kedacom.ctsp.authz.oauth2.service.ClientService;
import com.kedacom.ctsp.authz.oauth2.vo.ClientVO;
import com.kedacom.ctsp.logging.AccessLogger;
import com.kedacom.ctsp.orm.param.Term;
import com.kedacom.ctsp.orm.param.TermEnum;
import com.kedacom.ctsp.web.controller.AbstractCrudController2;
import com.kedacom.ctsp.web.controller.message.ResponseMessage;
import com.kedacom.ctsp.web.controller.util.QueryParamUtil;
import com.kedacom.ctsp.web.entity.page.PagerResult;
import com.kedacom.ctsp.web.entity.param.QueryParamEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户端配置Controller
 *
 * @author xuwei
 * @create 2018-05-14 13:15
 **/
@RestController
@RequestMapping("/client")
@Api(tags = "client", description = "项目增删改查")
@Authorize(resources = AuthorizeConstant.AUTH_CLIENT)
public class OAuth2ClientController extends AbstractCrudController2<Client, String, ClientVO, ClientService> {

    @PostMapping
    @AccessLogger("SAVE")
    @ApiOperation(
            value = "创建数据",
            responseReference = "add"
    )
    @ApiResponses({@ApiResponse(
            code = 201,
            message = "创建成功,返回创建数据的ID"
    ), @ApiResponse(
            code = 401,
            message = "未授权"
    ), @ApiResponse(
            code = 403,
            message = "无权限"
    )})
    @Override
    @Authorize(resources = AuthorizeConstant.AUTH_CLIENT_ADD)
    public ResponseMessage<String> add(@RequestBody ClientVO data) {
        return super.add(data);
    }

    @Override
    @Authorize(resources = AuthorizeConstant.AUTH_CLIENT_QUERY)
    public ResponseMessage<PagerResult<ClientVO>> list(QueryParamEntity param, HttpServletRequest request) {
        QueryParamUtil.paddingTerms(param, request);
        Authentication authentication = Authentication.current().orElseThrow(UnauthorizedException::new);
        List<String> clients = this.service.getUserClient(authentication.getUser().getUsername()).stream().map(Client::getSign).collect(Collectors.toList());
        if (clients.size() == 0) {
            return ResponseMessage.ok();
        }
        param.addTerm(Term.build(Client.SIGN, TermEnum.in, new HashSet<>(clients)));
        ResponseMessage<PagerResult<ClientVO>> pagerResultResponseMessage = super.list(param, request);
        return pagerResultResponseMessage;
    }

    @Override
    @Authorize(resources = AuthorizeConstant.AUTH_CLIENT_UPDATE)
    public ResponseMessage<String> updateByPrimaryKey(@PathVariable String id, @RequestBody ClientVO data) {
        return super.patchByPrimaryKey(id, data);
    }

    @GetMapping("listForProject")
    @AccessLogger("listForProject")
    @ApiOperation(
            value = "根据动态条件查询数据",
            responseReference = "get"
    )
    @ApiResponses({@ApiResponse(
            code = 200,
            message = "查询成功"
    ), @ApiResponse(
            code = 401,
            message = "未授权"
    ), @ApiResponse(
            code = 403,
            message = "无权限"
    )})
    public ResponseMessage<PagerResult<Client>> listForProject(QueryParamEntity param, HttpServletRequest request) {
        QueryParamUtil.paddingTerms(param, request);
        PagerResult<Client> pagerResult = new PagerResult();
        pagerResult.setData(this.service.listForProject(param));
        pagerResult.setTotal((long) pagerResult.getData().size());
        return ResponseMessage.ok(pagerResult);
    }


    @GetMapping(
            path = {"/userClient/{username}"}
    )
    @AccessLogger("获取用户绑定的项目")
    @ApiOperation("获取用户绑定的项目")
    @Authorize(resources = AuthorizeConstant.AUTH_CLIENT_CURRENT)
    public ResponseMessage<List<Client>> getUserClient(@PathVariable String username) {
        return ResponseMessage.ok(this.service.getUserClient(username));
    }

    @GetMapping(
            path = {"/userClient/current/{username}"}
    )
    @AccessLogger("获取用户绑定的项目")
    @ApiOperation("获取用户绑定的项目")
    @Authorize(resources = AuthorizeConstant.AUTH_CLIENT_CURRENT)
    public ResponseMessage<List<Client>> getUserClientCurrent(@PathVariable String username) {
        return ResponseMessage.ok(this.service.getUserClient(username));
    }

    @PostMapping(
            path = {"/userClient/{id}"}
    )
    @AccessLogger("根据人员添加项目")
    @ApiOperation("根据人员添加项目")
    public ResponseMessage<List<Long>> addUserClient(@PathVariable Long id, @RequestBody List<String> clients) {
        return ResponseMessage.ok(this.service.addUserClient(id, clients));
    }
}
